<template>
  <div class="video-publish-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>发布新视频</h2>
      <p>请填写视频信息并上传视频文件</p>
    </div>
    <!-- 发布表单 -->
    <el-form
        ref="videoFormRef"
        :model="videoForm"
        :rules="formRules"
        label-width="120px"
        class="video-form"
    >
      <!-- 视频上传区域 -->
      <el-form-item label="上传视频" prop="videoUrl" class="upload-item">
        <SplitChunkUpload chunk-scene="share:video:chunks" scene-code="share:video" @uploadSuccess="uploadSuccess"  @uploadError="uploadError"></SplitChunkUpload>
      </el-form-item>
      <!-- 视频封面上传 -->
      <el-form-item label="视频封面" prop="cover">
        <el-upload
            class="cover-uploader"
            :action="$fileUpload"
            :headers="$getHeaders"
            :data="{sceneCode:'share:video:cover'}"
            :on-success="onCoverUploadSuccess"
            :on-error="onCoverUploadError"
            :before-upload="beforeCoverUpload"
            :limit="1"
            :file-list="coverFileList"
            accept="image/*"
        >
          <div class="cover-upload-area" v-if="!videoForm.cover">
            <el-icon class="upload-icon">
              <PictureRounded/>
            </el-icon>
            <p>点击上传封面或拖放至此</p>
          </div>
          <el-image
              v-if="videoForm.cover"
              :src="videoForm.cover"
              class="cover-preview"
              fit="cover"
          >
            <template>
              <el-button
                  icon="Delete"
                  circle
                  @click.stop="handleCoverRemove"
              />
            </template>
          </el-image>
          <template #tip>
            <p>支持JPG、PNG格式，建议尺寸16:9，大小不超过5MB</p>
          </template>
        </el-upload>
      </el-form-item>
      <!-- 视频基本信息 -->
      <el-form-item label="视频标题" prop="title">
        <el-input
            v-model="videoForm.title"
            placeholder="请输入视频标题"
            maxlength="100"
            show-word-limit
        />
      </el-form-item>
      <el-form-item label="分类">
        <el-cascader v-model="videoForm.categoryId" :options="categoryTree" :props="props" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-select
            v-model="videoForm.tags"
            multiple
            filterable
            allow-create
            remote
            :remote-method="searchTags"
            :loading="tagLoading"
            placeholder="请选择或输入标签"
            style="width: 100%"
        >
          <el-option
              v-for="item in filteredTags"
              :key="item.tagId"
              :label="item.name"
              :value="item.tagId"
          >
            <div class="tag-option">
              <span>{{ item.name }}</span>
              <span class="tag-count">({{ item.videoCount || 0 }}个视频)</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视频描述" prop="description">
        <el-input
            v-model="videoForm.description"
            placeholder="请输入视频描述（可选）"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
        />
      </el-form-item>
      <!-- 视频属性设置 -->
      <el-form-item label="可见性" prop="privacy">
        <el-radio-group v-model="videoForm.privacy">
          <el-radio :value="0">公开</el-radio>
          <el-radio :value="1">仅自己可见</el-radio>
          <el-radio :value="2">仅校内可见</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否原创" prop="isOriginal">
        <el-switch
            v-model="videoForm.isOriginal"
            active-value="1"
            inactive-value="0"
            active-text="原创"
            inactive-text="非原创"
        />
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item class="form-actions">
        <el-button
            type="primary"
            @click="handleSubmit(videoFormRef)"
            :loading="isSubmitting"
        >
          发布视频
        </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted,computed} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage,ElMessageBox} from 'element-plus';
import SplitChunkUpload from '@/components/uploader/SplitChunkUpload.vue'
import {
  UploadFilled,
  PictureRounded,
  Delete
} from '@element-plus/icons-vue';
import {useRouter} from 'vue-router';
import { shareCoverUpload} from '@/util'
import {reqCreateShareVideo} from "@/api/share";
import {reqGetCategoryTreeList} from "@/api/share/category";
import {reqGetTagList} from "@/api/share/tag";

// 表单数据
const videoForm = reactive({
  title: '',
  description: '',
  categoryId: '',
  tags: [],
  videoUrl: '', // 视频文件URL（后端返回）
  cover: '', // 封面URL
  privacy: 0, // 0-公开 1-私有 2-校内可见
  isOriginal: 1, // 1-原创 0-非原创
})
let categoryTree=ref([])
let props= reactive({
  value:'categoryId',
  label:'name',
  children:'children',
  emitPath:false
});
// 状态管理
const videoFormRef = ref<FormInstance>();
const videoFileList = ref<any[]>([]);
const coverFileList = ref<any[]>([]);
const isUploading = ref(false);
const isSubmitting = ref(false);
const uploadProgress = ref(0);
const router = useRouter();

// 表单验证规则
const formRules = reactive<FormRules>({
  title: [
    {required: true, message: '请输入视频标题', trigger: 'blur'},
    {min: 2, max: 100, message: '标题长度在2-100个字符之间', trigger: 'blur'}
  ],
  videoFile: [
    {required: true, message: '请上传视频文件', trigger: 'change'}
  ]
});


// 处理视频上传
const uploadSuccess = (filePath: string) => {
  videoForm.videoUrl = filePath
}

let uploadError=()=>{
  ElMessage.error('上传失败，请重试');
}
let getCategoryTree=async ()=>{
  let res=await reqGetCategoryTreeList()
  categoryTree.value=res.data
}
// 封面上传前校验
const beforeCoverUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件（JPG、PNG格式）');
    return false;
  }
  const isLt5MB = file.size / 1024 / 1024 < 5;
  if (!isLt5MB) {
    ElMessage.error('封面图片大小不能超过5MB');
    return false;
  }
  return true;
};

// 封面上传成功处理
const onCoverUploadSuccess = (response: any) => {
  if (response.code === 200) {
    videoForm.cover = response.data.visitPath;
    console.log("上传结果", response.data.visitPath)
    ElMessage.success('封面上传成功');
  } else {
    ElMessage.error('封面上传失败：' + (response.msg || '未知错误'));
  }
};

// 封面上传失败处理
const onCoverUploadError = () => {
  ElMessage.error('封面上传失败，请重试');
};

// 移除封面
const handleCoverRemove = () => {
  videoForm.cover = '';
  coverFileList.value = [];
};

// 提交表单
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      reqCreateShareVideo(videoForm)
    } else {
      console.log('error submit!', fields)
    }
  })
  isSubmitting.value = false;
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm(
      '确定要取消发布吗？已填写的内容将会丢失',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    router.back();
  }).catch(() => {
    // 取消操作，留在当前页面
  });
};
// 标签相关状态
const tagList = ref([]); // 存储从后端获取的标签列表
const tagLoading = ref(false); // 标签加载状态
const tagSearch = ref(''); // 标签搜索关键词

// 计算属性：过滤后的标签列表
const filteredTags = computed(() => {
  if (!tagSearch.value) {
    return tagList.value;
  }
  const searchText = tagSearch.value.toLowerCase();
  return tagList.value.filter(tag =>
      tag.name.toLowerCase().includes(searchText)
  );
});

// 获取标签列表
const getTagList = async (params = {}) => {
  try {
    tagLoading.value = true;
    const res = await reqGetTagList(params);
    tagList.value = res.data;
  } catch (error) {
    console.error('获取标签列表失败:', error);
    ElMessage.error('获取标签列表失败');
  } finally {
    tagLoading.value = false;
  }
};

// 标签搜索方法
const searchTags = (query: string) => {
  tagSearch.value = query;
  getTagList({ name: query });
};

onMounted(() => {
  getCategoryTree()
  getTagList();
});
</script>

<style lang="scss" scoped>
.video-publish-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
}

.page-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;

  h2 {
    margin: 0 0 10px;
    font-size: 22px;
    color: #333;
  }

  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.video-form {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.upload-item {
  margin-bottom: 25px;

  .video-uploader {
    width: 100%;
    border: 1px dashed #ccc;
    border-radius: 6px;
    padding: 40px 20px;
    text-align: center;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  .upload-tip {
    margin-top: 10px;
    color: #666;
    font-size: 12px;

    .progress-bar {
      width: 300px;
      margin-top: 5px;
    }
  }
}

.cover-uploader {
  .cover-upload-area {
    width: 320px;
    height: 180px;
    border: 1px dashed #ccc;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
      background-color: #f5f7fa;
    }

    .upload-icon {
      font-size: 24px;
      color: #999;
      margin-bottom: 10px;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }

  .cover-preview {
    width: 320px;
    height: 180px;
    border-radius: 6px;
    border: 1px solid #eee;
  }
}

.form-actions {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;

  button {
    margin-right: 10px;
  }
}
.tag-option {
  display: flex;
  justify-content: space-between;
  width: 100%;

  .tag-count {
    color: #999;
    font-size: 12px;
    margin-left: 8px;
  }
}
</style>
